package com.tyj.movie.scheduled;

import com.tyj.movie.service.MovieService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 日期: 2021/7/6 14:22
 * 作者: 谭友杰
 * 类说明:  定时任务
 */
@Component
@Slf4j
public class MyScheduled {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    MovieService movieService;



    static final String movie_lock="movie:update:lock";
    static final String comment_lock="movie:comment:lock";


    /**
     * 刷新热映电影 上映电影 热播电影 定时任务
     * 每三小时执行一次
     */
    @Scheduled(cron = "0 0/10 * * * ? ")
    public void updateMainPageMovieScheduled(){
        log.debug("执行主页电影更新操作======================================================");
        //处理程序幂等性
        RLock lock = redissonClient.getLock(movie_lock);
        try {
            //避免死锁问题 若该锁10秒没未返回任务 则自动释放锁
            lock.lock(10, TimeUnit.SECONDS);

            //执行更新
            movieService.updateComingMovies();
            movieService.updateHotShowMovie();
            movieService.updateHotMovies();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 统计评论
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void statCommentLevel(){
        log.debug("执行电影评论统计更新操作======================================================");

        RLock comment_lock = redissonClient.getLock("comment_lock");
        try {
            comment_lock.lock(10, TimeUnit.SECONDS);
            movieService.statCommentLevel();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            comment_lock.unlock();
        }


    }

}
